package com.bjpowernode.springsecurity03.handle;

import com.bjpowernode.springsecurity03.domain.SysUser;
import com.bjpowernode.springsecurity03.util.JwtUtil;
import com.bjpowernode.springsecurity03.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        SysUser sysUser = (SysUser)authentication.getPrincipal();

        List<SimpleGrantedAuthority> permissions = sysUser.getPermissions();

        //将List<SimpleGrantedAuthority>转出List<String>
        List<String> authority = new ArrayList<>();
        for (SimpleGrantedAuthority permission : permissions) {
            authority.add(permission.getAuthority());
        }

        //生成jwt
        String jwt = JwtUtil.creatToken(sysUser.getUserId(), sysUser.getUsername(), authority);

        String userJson = objectMapper.writeValueAsString(sysUser);

        //存入redis  失效时间10分钟
        stringRedisTemplate.opsForValue().set("jwt:"+jwt, userJson,5, TimeUnit.MINUTES);


        //创建一个Result对象，封装登录成功信息
        Result result = new Result(200, "登录成功",jwt);
        //--------------新增结束---------------


        String jsonStr = objectMapper.writeValueAsString(result);

        response.getWriter().write(jsonStr);

    }
}
